package cn.itcast.dewu.rabbitUtils;

import cn.hutool.core.lang.UUID;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
@Slf4j
public class ReturnCallbackConfig implements ApplicationContextAware {
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        //获取rabbitTemplate
        RabbitTemplate rabbitTemplate = applicationContext.getBean(RabbitTemplate.class);
        String id = applicationContext.getId();
        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString(true));
        //设置returnCallback
        rabbitTemplate.setReturnCallback((message, replayCode, replayText, exchange, routingKey) -> {
            //投递失败 记录一下日志 并重新发送消息
            log.info("消息发送失败,应答码{},原因{},交换机{},路由键{},消息{}",
                    replayCode, replayText, exchange, routingKey, message.toString());
            //重新发送消息
            rabbitTemplate.convertAndSend(exchange,routingKey,message,correlationData);
        });

    }
}
